package com.haoyeteng.sxbd.modular.business.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.haoyeteng.sxbd.core.util.PDFUtil;
import com.haoyeteng.sxbd.modular.business.dao.ContractMapper;
import com.haoyeteng.sxbd.modular.business.model.Contract;
import com.haoyeteng.sxbd.modular.business.model.OrderDtl;
import com.haoyeteng.sxbd.modular.business.service.IContractService;

/**
 * <p>
 * 合同管理 服务实现类
 * </p>
 *
 * @author haoyeteng123
 * @since 2019-10-04
 */
@Service
public class ContractServiceImpl extends ServiceImpl<ContractMapper, Contract> implements IContractService {
	
	@Override
	public ResponseEntity<?> exportPdf(Contract contract, List<OrderDtl> orderDtlList) {
		HttpHeaders headers = new HttpHeaders();

        /**
         * 数据导出(PDF 格式)
         */
        Map<String, Object> dataMap = new HashMap<>(16);
        dataMap.put("contract",contract);
        dataMap.put("orderDtlList",orderDtlList);
        String htmlStr = PDFUtil.freemarkerRender(dataMap, "templates/contract_export.ftl");
        byte[] pdfBytes = PDFUtil.createPDF(htmlStr, "static/font/simsun.ttc");
        if (pdfBytes != null && pdfBytes.length > 0) {
            String fileName = System.currentTimeMillis() + (int) (Math.random() * 90000 + 10000) + ".pdf";
            headers.setContentDispositionFormData("attachment", fileName);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            return new ResponseEntity<byte[]>(pdfBytes, headers, HttpStatus.OK);
        }

        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        return new ResponseEntity<String>("{ \"code\" : \"404\", \"message\" : \"not found\" }",
                headers, HttpStatus.NOT_FOUND);
	}

	@Override
	public List<Map<String, Object>> selectMyContractList(Page<Contract> page, String contractStatus, String contractNo,
			Integer userId) {
		return this.baseMapper.selectMyContractList(page, contractStatus, contractNo, userId);
	}

	@Override
	public List<Map<String, Object>> selectContractList(Page<Contract> page, String contractStatus, String contractNo,
			String orderId, String applyTime) {
		return this.baseMapper.selectContractList(page, contractStatus, contractNo, orderId, applyTime);
	}

}
